import * as baseApi from '@/api'
// import { resetRouter } from '@/router'

const state = {
  token: '',
  refToken: '',
  uId: 0,
  name: '',
  avatar: '',
  account: '',
  gender: '',
  email: '',
  headIcon: '',
  nickName: '',
  defPageSize: 20,
  introduction: '',
  roles: [],
  authInfo: [],
  platformId: 0, // 当前平台
  platformInfo: [] // 拥有的平台
}

const mutations = {
  SET_TOKEN: (state, obj) => {
    // console.log('设置登录状态：')
    // console.log(obj)
    state.uId = obj.uId
    state.token = obj.token
    state.refToken = obj.refToken
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_AUTHINFO: (state, authInfo) => {
    // console.log(authInfo)
    state.authInfo = authInfo
  }
}

/**
 * 调用例子 dispatch只能传入一个参数 可返回数据 注意这是异步调用要带上await
 * this.$store.dispatch('user/login', this.loginForm)
 */
const actions = {
  // 系统登录
  async login({ commit }, loginInfo) {
    var res = await baseApi.sysUserLogin({ account: loginInfo.username, password: loginInfo.password, platformId: loginInfo.platformId },
      loginInfo.vue, loginInfo.loadingKey)
    if (res.ok) {
      commit('SET_TOKEN', {
        uId: res.body.uId,
        token: res.body.token,
        refToken: res.body.refToken
      })
      // 处理下权限信息
      var handleAuthInfo = function(authInfo) {
        for (let i = 0; i < authInfo.length; i++) {
          const e = authInfo[i]
          // 将meta转换成对象
          e.meta = JSON.parse(e.meta)
          // 检查子节点
          if (e.children) {
            handleAuthInfo(e.children)
          }
        }
      }
      handleAuthInfo(res.body.authInfo)
      commit('SET_NAME', res.body.adminInfo.nickName)
      commit('SET_AVATAR', res.body.adminInfo.headIcon)
      commit('SET_AUTHINFO', res.body.authInfo)
      commit('SET_INTRODUCTION', res.body.adminInfo.description)
      return true
    } else {
      return false
    }
  },
  // 系统退出
  async logout({ commit, state, dispatch }, logoutInfo) {
    var res = await baseApi.sysUserSignOut(logoutInfo.vue, logoutInfo.loadingKey)
    if (res.ok) {
      commit('SET_TOKEN', {
        uId: '',
        token: '',
        refToken: ''
      })
      commit('SET_NAME', '')
      commit('SET_AVATAR', '')
      commit('SET_AUTHINFO', [])
      commit('SET_INTRODUCTION', '')

      dispatch('tagsView/delAllViews', null, { root: true })
      return true
    } else {
      return false
    }
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
